package com.project.school_flate.serviceimpl.shop;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.project.school_flate.dto.shop.ShopCommoditySpecsTypeDto;
import com.project.school_flate.entity.shop.ShopCommodity;
import com.project.school_flate.entity.shop.ShopCommoditySpecs;
import com.project.school_flate.entity.shop.ShopCommoditySpecsType;
import com.project.school_flate.entity.table.shop.ShopCommoditySpecsTable;
import com.project.school_flate.entity.table.shop.ShopCommoditySpecsTypeTable;
import com.project.school_flate.mapper.shop.ShopCommodityMapper;
import com.project.school_flate.mapper.shop.ShopCommoditySpecsMapper;
import com.project.school_flate.mapper.shop.ShopCommoditySpecsTypeMapper;
import com.project.school_flate.service.shop.ShopCommoditySpecsTypeService;
import com.project.school_flate.util.PoToDTO;
import com.project.school_flate.util.Result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 *  服务层实现。
 *
 * @author 马维健
 * @since 2024/1/2
 */
@Service
public class ShopCommoditySpecsTypeServiceImpl extends ServiceImpl<ShopCommoditySpecsTypeMapper, ShopCommoditySpecsType> implements ShopCommoditySpecsTypeService {

    @Autowired
    private ShopCommoditySpecsTypeMapper oShopCommoditySpecsTypeMapper;

    @Autowired
    private ShopCommoditySpecsMapper oShopCommoditySpecsMapper;

    @Autowired
    private ShopCommodityMapper oShopCommodityMapper;

    /**
     * 获取商品规格类型
     * @param oShopCommoditySpecsTypeDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getShopCommoditySpecsType(ShopCommoditySpecsTypeDto oShopCommoditySpecsTypeDto) throws Exception {
        List<ShopCommoditySpecsType> oShopCommoditySpecsTypeList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderBy("no desc");
        //是否分页
        if(oShopCommoditySpecsTypeDto.getPage() != null && oShopCommoditySpecsTypeDto.getLimit() != null){
            Page<ShopCommoditySpecsType> ShopCommoditySpecsTypePage = oShopCommoditySpecsTypeMapper.paginateWithRelations(oShopCommoditySpecsTypeDto.getPage(),oShopCommoditySpecsTypeDto.getLimit(),queryWrapper);
            oShopCommoditySpecsTypeList = ShopCommoditySpecsTypePage.getRecords();
            total = ShopCommoditySpecsTypePage.getTotalRow();
        }else{
            oShopCommoditySpecsTypeList = oShopCommoditySpecsTypeMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oShopCommoditySpecsTypeList.size();
        }
        //PoToDto
        List<ShopCommoditySpecsTypeDto> oShopCommoditySpecsTypeDtoList = (List<ShopCommoditySpecsTypeDto>) PoToDTO.poToDtoList(oShopCommoditySpecsTypeList,new ShopCommoditySpecsTypeDto());
        return Result.ok(oShopCommoditySpecsTypeDtoList,total);
    }

    /**
     * 添加商品规格类型
     * @param oShopCommoditySpecsTypeDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result addShopCommoditySpecsType(ShopCommoditySpecsTypeDto oShopCommoditySpecsTypeDto) throws Exception {
        ShopCommoditySpecsType oShopCommoditySpecsType = new ShopCommoditySpecsType();
        PoToDTO.poToDto(oShopCommoditySpecsTypeDto,oShopCommoditySpecsType);
        if(oShopCommoditySpecsTypeMapper.insert(oShopCommoditySpecsType) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加商品规格类型失败");
        }
        return Result.ok("添加商品规格类型成功");
    }

    /**
     * 修改商品规格类型
     * @param oShopCommoditySpecsTypeDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result updateShopCommoditySpecsType(ShopCommoditySpecsTypeDto oShopCommoditySpecsTypeDto) throws Exception {
        ShopCommoditySpecsType oShopCommoditySpecsType = new ShopCommoditySpecsType();
        PoToDTO.poToDto(oShopCommoditySpecsTypeDto,oShopCommoditySpecsType);
        if(oShopCommoditySpecsTypeMapper.update(oShopCommoditySpecsType) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("修改商品规格类型失败");
        }
        return Result.ok("修改商品规格类型成功");
    }

    /**
     * 删除商品规格类型
     * @param oShopCommoditySpecsTypeDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result deleteShopCommoditySpecsType(ShopCommoditySpecsTypeDto oShopCommoditySpecsTypeDto) throws Exception {
        ShopCommoditySpecsType oShopCommoditySpecsType = new ShopCommoditySpecsType();
        PoToDTO.poToDto(oShopCommoditySpecsTypeDto,oShopCommoditySpecsType);
        if(oShopCommoditySpecsTypeMapper.deleteById(oShopCommoditySpecsType.getId()) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("删除商品规格类型失败");
        }
        return Result.ok("删除商品规格类型成功");
    }

    /**
     * 获取商品规格类型（用户）
     * @param oShopCommoditySpecsTypeDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getShopCommoditySpecsTypeUser(ShopCommoditySpecsTypeDto oShopCommoditySpecsTypeDto) throws Exception {
        List<ShopCommoditySpecsType> oShopCommoditySpecsTypeList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderBy("no desc");
        //是否分页
        if(oShopCommoditySpecsTypeDto.getPage() != null && oShopCommoditySpecsTypeDto.getLimit() != null){
            Page<ShopCommoditySpecsType> ShopCommoditySpecsTypePage = oShopCommoditySpecsTypeMapper.paginateWithRelations(oShopCommoditySpecsTypeDto.getPage(),oShopCommoditySpecsTypeDto.getLimit(),queryWrapper);
            oShopCommoditySpecsTypeList = ShopCommoditySpecsTypePage.getRecords();
            total = ShopCommoditySpecsTypePage.getTotalRow();
        }else{
            oShopCommoditySpecsTypeList = oShopCommoditySpecsTypeMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oShopCommoditySpecsTypeList.size();
        }
        //PoToDto
        List<ShopCommoditySpecsTypeDto> oShopCommoditySpecsTypeDtoList = (List<ShopCommoditySpecsTypeDto>) PoToDTO.poToDtoList(oShopCommoditySpecsTypeList,new ShopCommoditySpecsTypeDto());
        return Result.ok(oShopCommoditySpecsTypeDtoList,total);
    }

    /**
     * 批量添加商品规格类型
     * @param oShopCommoditySpecsTypeDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result batchAddShopCommoditySpecsType(ShopCommoditySpecsTypeDto oShopCommoditySpecsTypeDto) throws Exception {
        //删除以前的商品规格类型
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ShopCommoditySpecsTypeTable.SHOP_COMMODITY_SPECS_TYPE.COMMODITY_ID.eq(oShopCommoditySpecsTypeDto.getCommodityId()));
        oShopCommoditySpecsTypeMapper.deleteByQuery(queryWrapper);
        //删除以前的商品规格
        queryWrapper = new QueryWrapper();
        queryWrapper.where(ShopCommoditySpecsTable.SHOP_COMMODITY_SPECS.COMMODITY_ID.eq(oShopCommoditySpecsTypeDto.getCommodityId()));
        oShopCommoditySpecsMapper.deleteByQuery(queryWrapper);
        if(CollectionUtils.isNotEmpty(oShopCommoditySpecsTypeDto.getShopCommoditySpecsTypeList())){
          //获取商品信息
            ShopCommodity oShopCommodity = oShopCommodityMapper.selectOneById(oShopCommoditySpecsTypeDto.getCommodityId());
            if(oShopCommodity == null){
                return Result.error("商品不存在");
            }
            //再添加商品规格类型
            List<ShopCommoditySpecsType> oShopCommoditySpecsTypeList = oShopCommoditySpecsTypeDto.getShopCommoditySpecsTypeList();
            for(ShopCommoditySpecsType oShopCommoditySpecsType : oShopCommoditySpecsTypeList){
                oShopCommoditySpecsType.setCommodityId(oShopCommoditySpecsTypeDto.getCommodityId());
            }
            if(oShopCommoditySpecsTypeMapper.insertBatch(oShopCommoditySpecsTypeList) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error("添加店铺规则失败");
            }
            //再添加商品规格
            List<ShopCommoditySpecs> oShopCommoditySpecsList = new ArrayList<>();
            for(ShopCommoditySpecsType oShopCommoditySpecsType : oShopCommoditySpecsTypeList){
                for(ShopCommoditySpecs oShopCommoditySpecs : oShopCommoditySpecsType.getShopCommoditySpecsList()){
                    oShopCommoditySpecs.setCommodityId(oShopCommoditySpecsTypeDto.getCommodityId());
                    oShopCommoditySpecs.setCommoditySpecsTypeId(oShopCommoditySpecsType.getId());
                    if(oShopCommoditySpecs.getOriginalPrice() == null){
                        oShopCommoditySpecs.setOriginalPrice(0.0);
                    }
                    //判断是否参与储蓄折扣
                    if(oShopCommoditySpecs.getIsInSave() == 0){
                        oShopCommoditySpecs.setMemberPrice(oShopCommoditySpecs.getOriginalPrice());
                        oShopCommoditySpecs.setSaveDiscountRatio(1.0);
                    }else{
                        if(oShopCommoditySpecs.getMemberPrice() == null){
                            return Result.error("需要填写会员价");
                        }
                        if(oShopCommoditySpecs.getMemberPrice().compareTo(oShopCommoditySpecs.getOriginalPrice()) >= 0){
                            return Result.error("会员价小于等于原价");
                        }
                        oShopCommoditySpecs.setSaveDiscountRatio(oShopCommoditySpecs.getMemberPrice() / oShopCommoditySpecs.getOriginalPrice());
                    }
                    oShopCommoditySpecsList.add(oShopCommoditySpecs);
                }
            }
            if(oShopCommoditySpecsMapper.insertBatch(oShopCommoditySpecsList) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error("添加店铺规则失败");
            }
        }
        return Result.ok("添加店铺规则成功");
    }

}
